define [
	'jquery'
	'sammy/plugins/sammy.template-0.7.1.min.js'
	'jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	S = {}
	$.fn.mb_donation_detail = (SamCtx) ->
	
		# Global variable
		$this = $(@)
		S = SamCtx
		$tpl = $this.find('.tpl').hide()
		
		# Initialization and table creation
		unless @mb_plugin()
			@mb_plugin 'donation_detail'
			
			# Main subscription event to handle published donation id and display it in the current page
			$.subscribe "mb.donation", (e, arg) =>
				_dnID = arg['id']
				
				# Open couch document for reading
				$.couch.db("vcn-members").openDoc _dnID, {
					success: (doc) ->
						if doc.cash then doc.cash_yn = "Yes" else doc.cash_yn = "No"
						doc.donation_amount = "$#{parseFloat(doc.donation_amount).toFixed(2)}"
						
						# Acquire the template for the form and fill in content
						content = S.content $tpl, doc
						$this.find('.content').empty().append content
						
						# Remove all the fields (rows) that are blank
						$this.find('.content tr > td:odd').each () ->
							$(@).parent().remove() if $(@).text().length is 0
					}

				# Define click event handling for Print Receipt button
				$this.find('[name="view_receipt"]').on 'click', ->
					$.publish "mb.donation", {id: _dnID, for: "receipt"}
					S.app.setLocation "#/view_receipt"
					
				return
		return @
	return
